#include "OsgNodeLayer.h"
#include "OsgUserData.h"

#define GET_DATA(item)\
if(!item)\
    return;\
auto data = fromBaseToCurrent<OsgUserData,QObjectUserData>(item->userData(OSG_NODE_INDEX));

OsgNodeLayer::OsgNodeLayer()
{
    group = new osg::Group();
}

OsgNodeLayer::~OsgNodeLayer()
{

}

void OsgNodeLayer::setVisible(bool visible)
{
    if(isVisible() == visible)
		return;
}

bool OsgNodeLayer::loadFromJson(const QString& json)
{
    return false;
}

QString OsgNodeLayer::toJson()const
{
    return QString();
}

void OsgNodeLayer::appendChild(AbstractItem* item)
{
	GET_DATA(item)
	if(data)
	{
		auto node = data->node ? data->node : data->group;
		group->addChild(node);
		AbstractLayer::appendChild(item);
	}
}
	
void OsgNodeLayer::insertChild(int pos,AbstractItem* item)
{
	GET_DATA(item)
	if(data)
	{
		auto node = data->node?data->node:data->group;
		group->insertChild(pos,node);
		AbstractLayer::insertChild(pos,item);
	}
}
	
int OsgNodeLayer::indexOfChild(AbstractItem* item)
{
	if(!item)
		return -1;

	auto data = fromBaseToCurrent<OsgUserData,QObjectUserData>(item->userData(OSG_NODE_INDEX));
	if(data)
	{
		auto node = data->node?data->node:data->group;
		return group->getChildIndex(node);
	}
	return -1;
}

void OsgNodeLayer::removeChild(int pos)
{
	if(pos>0)
	{
		group->removeChild(pos);
		AbstractLayer::removeChild(pos);
	}
}

void OsgNodeLayer::removeChild(AbstractItem* item)
{
	if(item)
	{
		auto data = fromBaseToCurrent<OsgUserData,QObjectUserData>(item->userData(OSG_NODE_INDEX));
		if(!data)
			return;

		auto node = data->node?data->node:data->group;
		group->removeChild(node);
		AbstractLayer::removeChild(item);
	}
}